<template>
  <div class="login">
    <el-form
      :model="form"
      status-icon
      ref="form"
      label-width="100px"
      label-position="top"
      :rules="rules"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input type="text" v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="onSubmit">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Form } from "element-ui";
import { login } from "@/services/user";
export default Vue.extend({
  name: "LoginIndex",
  data() {
    return {
      loading: false,
      form: {
        phone: "",
        password: "",
      },
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1\d{10}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: "请输入密码长度6-18", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      this.loading = true;
      try {
        await (this.$refs.form as Form).validate();
        const {
          data: { state, message, content },
        } = await login(this.form);

        if (state !== 1) {
          this.$message.error(message);
        } else {
          this.$store.commit("setUser", content);
          this.$router.push((this.$route.query.redirect as string) || "/");
          this.$message.success("登录成功！");
        }
      } catch (error) {
        console.log(error);
        this.$message.error("登录失败！");
      }
      this.loading = false;
    },
  },
});
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-form {
    width: 40%;
    padding: 0 20px;
    background: #fff;
    border-radius: 4px;
  }
  .el-button {
    width: 100%;
  }
}
</style>
